//
//  SelectCityViewController.m
//  动起来
//
//  Created by 李成鹏 on 16/8/16.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "SelectCityViewController.h"
#import "CityManager.h"
#import "OtherCityTableViewCell.h"

@interface SelectCityViewController () <UITableViewDataSource, UITableViewDelegate> {
    BOOL _showArea; // 是否显示县区
    NSString *_currentCity;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *keyArray;
@property (nonatomic, strong) NSDictionary *dataDict;
@property (nonatomic, strong) NSArray *hotCityArray;

@end

@implementation SelectCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setData];
    [self initSubViews];
}

- (void)initSubViews {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:(UITableViewStylePlain)];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"citysCell"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OtherCityTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"otherCell"];
    [self.view addSubview:_tableView];
}

- (void)setData {
    
    _showArea = NO;
    _currentCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentCity"];
    self.keyArray = [[CityManager manager] getKeyArray];
    self.dataDict = [[CityManager manager] getDataDict];
    self.hotCityArray = [[CityManager manager] getHotCity];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.keyArray.count + 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section <= 3) {
        return 1;
    }
    NSArray *cityArray = self.dataDict[self.keyArray[section - 4]];
    return cityArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section <= 3) {
        if (indexPath.section == 0) {
            if (_showArea) {
                NSInteger count = [[[CityManager manager] getAreaWithCityName:_currentCity] count];
                if (count % 3 == 0) {
                    return (count / 3) * 30 + (count / 3 - 1) * 10 + 20;
                } else {
                    return (count / 3 + 1) * 30 + (count / 3) * 10 + 20;
                }
            } else {
                return 0;
            }
        } else if (indexPath.section == 1) {
            return 50;
        } else if (indexPath.section == 2) {
            NSArray *array =  [[NSUserDefaults standardUserDefaults] objectForKey:@"RecentlyCity"];
            if (array.count % 3 == 0) {
                return (array.count / 3) * 30 + (array.count / 3 - 1) * 10 + 20;
            } else {
                return (array.count / 3 + 1) * 30 + (array.count / 3) * 10 + 20;
            }
        } else if (indexPath.section == 3) {
            NSInteger count = [[[CityManager manager] getHotCity] count];
            if (count % 3 == 0) {
                return (count / 3) * 30 + (count / 3 - 1) * 10 + 20;
            } else {
                return (count / 3 + 1) * 30 + (count / 3) * 10 + 20;
            }
        }
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headrView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 35)];
    if (section == 0) {
        headrView.backgroundColor = [UIColor whiteColor];
        UIButton *btnGetArea = [UIButton buttonWithType:UIButtonTypeCustom];
        btnGetArea.frame = CGRectMake(0, 0, headrView.frame.size.width, 35);
        btnGetArea.titleEdgeInsets = UIEdgeInsetsMake(0, headrView.frame.size.width - 100, 0, 0);
        if (_showArea) {
            [btnGetArea setTitle:@"选择区县∧" forState:(UIControlStateNormal)];
        } else {
            [btnGetArea setTitle:@"选择区县∨" forState:(UIControlStateNormal)];
        }
        [btnGetArea addTarget:self action:@selector(btnClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [btnGetArea setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
        btnGetArea.titleLabel.font = [UIFont systemFontOfSize:15];
        btnGetArea.backgroundColor = [UIColor clearColor];
        [headrView addSubview:btnGetArea];
    } else {
        headrView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    
    UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, headrView.frame.size.width - 10, 35)];
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor darkGrayColor];
    if (section == 0) {
        if (_currentCity == nil || [_currentCity isEqualToString:@""]) {
            lblTitle.text = [NSString stringWithFormat:@"当前：%@", @"未定位"];
        } else {
            lblTitle.text = [NSString stringWithFormat:@"当前：%@", _currentCity];
        }
    } else if (section == 1) {
        lblTitle.text = @"当前定位城市";
    } else if (section == 2) {
        lblTitle.text = @"最近访问的城市";
    } else if (section == 3) {
        lblTitle.text = @"热门城市";
    } else {
        lblTitle.text = self.keyArray[section - 4];
    }
    [headrView addSubview:lblTitle];
    return headrView;
    
}

- (void)btnClick:(UIButton *)sender{
    if (_showArea) {
        _showArea = NO;
    } else {
        _showArea = YES;
    }
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section > 3) {
        NSArray *cityArray = self.dataDict[self.keyArray[indexPath.section - 4]];
        NSDictionary *city = cityArray[indexPath.row];
        [[NSUserDefaults standardUserDefaults] setObject:city[@"name"] forKey:@"currentCity"];
        NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"RecentlyCity"]];
        if (![array containsObject:city[@"name"]]) {
            if (array.count == 10) {
                [array removeLastObject];
            }
        } else {
            [array removeObject:city[@"name"]];
        }
        [array insertObject:city[@"name"] atIndex:0];
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"RecentlyCity"];
        
        self.selectOK();
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section <= 3) {
        OtherCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"otherCell" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            if (_showArea) {
                cell.cityArray = [[CityManager manager] getAreaWithCityName:_currentCity];
            } else {
                cell.cityArray = @[];
            }
        } else if (indexPath.section == 1) {
            cell.cityArray = @[@"北京"]; // 这里要改成定位到的城市
        } else if (indexPath.section == 2) {
            NSArray *array =  [[NSUserDefaults standardUserDefaults] objectForKey:@"RecentlyCity"];
            cell.cityArray = array;
        } else if (indexPath.section == 3) {
            cell.cityArray = [[CityManager manager] getHotCity];
        }
        
        cell.citySelect = ^() {
            self.selectOK();
            [self.navigationController popViewControllerAnimated:YES];
        };
        
        return cell;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"citysCell" forIndexPath:indexPath];
    NSArray *cityArray = self.dataDict[self.keyArray[indexPath.section - 4]];
    NSDictionary *city = cityArray[indexPath.row];
    cell.textLabel.text = city[@"name"];
    return cell;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
